local proto = require("src.kit.core.proto")
local path = require("src.kit.core.path")
local log = proto.class("log")

log.color = {0, 1, 2, 3}
log.names = {"verbose", "info", "warn", "error"}

local function setConsoleColor(color)
    if ext and ext.setConsoleColor then ext:setConsoleColor(color) end
end

local function getLog(level, msg)
    if level >= 2 then msg = debug.traceback(msg, 2) end
    return msg
end

function log:ctor(level)
    self.__level = level
    self.__list = {}

end

function log:get_file_handler()
    if io.type(self.__filehandler) then return self.__filehandler end
    local writable = path:get_writable_path()
    local outpath = ("%s%s.log"):format(writable, log.names[self.__level])
    self.__filehandler = io.open(outpath, "w")
    return self.__filehandler
end

function log:push(msg)
    local info = debug.getinfo(2, "Sl")
    local fmt = "@%s\n@file: %s\n@line: %s\n@msg: %s"
    local tag = self.__names[self.__level]
    if self.__level >= 2 then msg = debug.traceback(msg, 2) end
    msg = fmt:format(tag, info.short_src, info.currentline, msg)
    table.insert(self.__list[tag], msg)
    setConsoleColor(log.color)
    print(msg)
    setConsoleColor(0)
end

function log:save()
    self:get_file_handler():write(table.concat(self.__list, "\n"))
end

function log:close()
    local file_handler = self:get_file_handler()
    file_handler:flush()
    file_handler:close()
end

return log
